﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Workflow.Runtime;
using System.Workflow.Runtime.Hosting;

namespace WorkflowManagement.Web
{
    /// <summary>
    /// A <see cref="IHttpModule">module</see> providing support needed by the <see cref="UI.WorkflowManager"/>.
    /// </summary>
    public class WorkflowManagerModule: IHttpModule, IDisposable
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="WorkflowManagerModule"/> class.
        /// </summary>
        public WorkflowManagerModule()
        {
        }
        
        #region IHttpModule Members

        /// <summary>
        /// Releases unmanaged and - optionally - managed resources
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                workflowRuntime.StopRuntime();
                workflowRuntime.Dispose();
            }
        }

        private WorkflowRuntime workflowRuntime;

        /// <summary>
        /// Initializes a module and prepares it to handle requests.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
        public void Init(HttpApplication context)
        {
            workflowRuntime = new WorkflowRuntime();
            ManualWorkflowSchedulerService manualScheduler = new ManualWorkflowSchedulerService();
            workflowRuntime.AddService(manualScheduler);
            workflowRuntime.StartRuntime();
            context.Application.Lock();
            context.Application["WorkflowRuntime"] = workflowRuntime;
            context.Application.UnLock();
        }

        #endregion
    }
}
